#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# C++ version Copyright (c) 2006-2007 Erin Catto http://www.box2d.org
# Python version by Ken Lauer / sirkne at gmail dot com
#
# This software is provided 'as-is', without any express or implied
# warranty.  In no event will the authors be held liable for any damages
# arising from the use of this software.
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
import cv2
import pygame
import torch
from Box2D import (b2EdgeShape, b2FixtureDef, b2PolygonShape, b2CircleShape, b2Color)
import os.path

from framework.framework import (Framework, main)
from visionBodyLearn.Agent import Agent


class ContactingInfo:

    def __init__(self):
        self.contactingBody = None
        self.contactingPoint = None


class BodyTypes(Framework):
    name = ""
    # description = "Change body type keys: (d) dynamic, (s) static, (k) kinematic"
    speed = 3  # platform speed

    def __init__(self):
        super(BodyTypes, self).__init__()
        self.world.gravity = (0.0, 0.0)
        self.iter = 0
        self.agent = Agent((480, 640))
        if os.path.isfile('savedModels/bodyInfo.m'):
            bodyInfo = torch.load('savedModels/bodyInfo.m')
            self.agent.bodyInfo = bodyInfo
        if os.path.isfile('savedModels/highLevelModels.m') and os.path.isfile('savedModels/highLevelModelKeys.m'):
            highLevelModels = torch.load('savedModels/highLevelModels.m')
            highLevelModelKeys = torch.load('savedModels/highLevelModelKeys.m')
            self.agent.highLevelModels = highLevelModels
            self.agent.highLevelModelKeys = highLevelModelKeys
        self.using_contacts = True
        self.circleColor = b2Color(0.9, 0.9, 0.9)
        self.ground_body = self.world.CreateStaticBody(
            shapes=[
                b2EdgeShape(vertices=[(-5, 0), (5, 0)]),
                b2EdgeShape(vertices=[(-5, 0), (-5, 10)]),
                b2EdgeShape(vertices=[(5, 0), (5, 10)]),
                b2EdgeShape(vertices=[(-5, 10), (5, 10)]),
            ],
        )
        self.circleBody = self.world.CreateDynamicBody(
            position=(2, 5),
            fixtures=b2FixtureDef(
                shape=b2CircleShape(radius=1),
                density=1,
                friction=1
            )
        )
        # self.blockingObject = self.world.CreateStaticBody(
        #     position=(0, 2),
        #     fixtures=b2FixtureDef(shape=b2PolygonShape(box=(1, 2)), density=2.0)
        # )
        # self.targetObject = self.world.CreateStaticBody(
        #     position=(0, 13.5),
        #     fixtures=b2FixtureDef(shape=b2PolygonShape(box=(1, 6.25)), density=2.0)
        # )

    def changeTheWorldByAction(self, action):
        if action == -1:
            return
        if action == 2:  # up
            f = self.circleBody.GetWorldVector(localVector=(0, 10))
            p = self.circleBody.GetWorldPoint(localPoint=(0.0, 0.0))
            self.circleBody.ApplyForce(f, p, True)
        elif action == 3:  # down
            f = self.circleBody.GetWorldVector(localVector=(0, -10))
            p = self.circleBody.GetWorldPoint(localPoint=(0.0, 0.0))
            self.circleBody.ApplyForce(f, p, True)
        elif action == 0:  # left
            f = self.circleBody.GetWorldVector(localVector=(-10, 0))
            p = self.circleBody.GetWorldPoint(localPoint=(0.0, 0.0))
            self.circleBody.ApplyForce(f, p, True)
        elif action == 1:  # right
            f = self.circleBody.GetWorldVector(localVector=(10, 0))
            p = self.circleBody.GetWorldPoint(localPoint=(0.0, 0.0))
            self.circleBody.ApplyForce(f, p, True)

    def Step(self, settings):
        super(BodyTypes, self).Step(settings)
        if self.iter > 10:
            self.iter = 0
        pygame.image.save(self.screen, 'outputImages/temp'+str(self.iter)+'.png')
        observedImage = cv2.imread('outputImages/temp'+str(self.iter)+'.png')
        cv2.imwrite('outputImages/resaved_temp'+str(self.iter)+'.png', observedImage[335:445, 265:375])
        act = self.agent.handle(observedImage)
        self.changeTheWorldByAction(act)
        self.iter += 1
        # circleContactingInfo = self.getCircleContacts()
        # for cci in circleContactingInfo:
        #     if cci.contactingBody == self.targetObject:
        #         print('won')

    def getCircleContacts(self):
        contactingInfo = []
        for contact in self.world.contacts:
            if contact.fixtureA.body == self.circleBody:
                ci = ContactingInfo()
                ci.contactingBody = contact.fixtureB.body
                ci.contactingManifold = contact.worldManifold
                contactingInfo.append(ci)
            elif contact.fixtureB.body == self.circleBody:
                ci = ContactingInfo()
                ci.contactingBody = contact.fixtureA.body
                ci.contactingPoint = contact.worldManifold.points[0]
                contactingInfo.append(ci)
        return contactingInfo


if __name__ == "__main__":
    main(BodyTypes)
